package com.aiyige.utils.TaskQueue;

import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.util.Log;

import timber.log.Timber;

public class TaskQueue {
    public static final int HANDLE_TASK = 1;
    Handler taskHandler;
    HandlerThread taskThread;
    Callback callback = null;
    String taskQueueName;

    public TaskQueue(String taskQueueName) {
        this.taskQueueName = taskQueueName;
    }

    public void onCreate() {
        taskThread = new HandlerThread(taskQueueName);
        taskThread.start();
        taskHandler = new Handler(taskThread.getLooper()) {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HANDLE_TASK:
                        if (callback != null) {
                            callback.handleTask(msg.obj);
                        }
                        break;
                }
            }
        };
    }

    public void submitTask(Object task) {
        if (task == null) return;
        if (!taskThread.isAlive()) return;
        Message msg = Message.obtain();
        msg.what = HANDLE_TASK;
        msg.obj = task;
        taskHandler.removeMessages(HANDLE_TASK);
        taskHandler.sendMessage(msg);
    }

    public void onDestroy() {
        try {
            if (taskThread != null) {
                taskThread.quit();
            }
        } catch (Exception e) {
            Timber.e("onDestroy:" + Log.getStackTraceString(e));
        }
    }

    public Callback getCallback() {
        return callback;
    }

    public void setCallback(Callback callback) {
        this.callback = callback;
    }

    public interface Callback {
        void handleTask(Object object);
    }
}
